/**************************************************************
  > File Name: sendShmget.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年02月23日 星期三 03时16分19秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <semaphore.h>
#include <sys/wait.h>
#include "sem.h"


int main(int argc, char **argv)
{
	key_t key;
	sem_t *semp = NULL;
	sem_t *semp1 = NULL;
	int shmid;
	char *shmp = NULL;
	char buf[BUFSIZE] = {0};
	int fd;

	key = ftok(PATHNAME, PROCID);
	if (key < 0)
	{
		perror("ftok()");
		exit(1);
	}
	
	shmid = shmget(key, 0, 0);
	if (shmid < 0)
	{
		perror("shmget()");
		exit(1);
	}
	
	shmp = shmat(shmid, NULL, 0);
	if (shmp == NULL)
	{
		perror("shmat()");
		exit(1);
	}
	
	fd = open(argv[1], O_RDONLY);
	if (fd < 0)
	{
		perror("open()");
		exit(1);
	}

	semp = sem_open(SEMPATH, 0);
	semp1 = sem_open(SEMPATH1, 0);

	int len;
	while ((len = read(fd, buf, BUFSIZE)) > 0)
	{
		sem_wait(semp);	
		strncpy(shmp, buf, len);
		sem_post(semp1);
		memset(buf, 0, BUFSIZE);
	}
/*	
	sem_wait(semp);
	strcpy(shmp, "\0");
	sem_post(semp1);
*/	
	shmdt(shmp);
	close(fd);
    exit(0);
}
